<template>
  <page-view>
    <page-header title="个人资料" :showBack="true"></page-header>
    <div class="content-box">
      <Form @submit="onSubmit">
        <cell-group inset>
          <!-- 通过 pattern 进行正则校验 -->
          <field
            v-model="nickName"
            name="昵称"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[{ required: true, message: '请输入昵称' }]"
          />
          <field
            type="text"
            v-model="user_phone"
            name="电话"
            label="电话"
            placeholder="请输入电话"
            :rules="[{ required: true, message: '请输入电话' }]"
          />
          <field
            type="text"
            v-model="user_email"
            name="邮箱"
            label="邮箱"
            placeholder="邮箱"
            :rules="[{ required: true, message: '请输入邮箱' }]"
          />
          <field name="radio" label="性别">
            <template #input>
              <radio-group v-model="user_sex" direction="horizontal">
                <radio name="男">男</radio>
                <radio name="女">女</radio>
              </radio-group>
            </template>
          </field>
          <field
            name="uploader"
            label="头像上传"
            v-model="user_photo"
            :rules="[{ required: true, message: '请上传头像' }]"
          >
            <template #input>
              <uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
                :max-size="500 * 1024"
                @oversize="onOversize"
              />
            </template>
          </field>

          <!-- 通过 validator 返回错误提示 -->
        </cell-group>

        <div style="margin: 16px">
          <Button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="正在注册"
            :disabled="loading"
            >提交</Button
          >
        </div>
      </Form>
    </div>
  </page-view>
</template>

<script>
import PageView from "@/components/PageView.vue";
import PageHeader from "@/components/PageHeader.vue";
import { ref, getCurrentInstance, reactive, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import {
  Form,
  Field,
  CellGroup,
  Button,
  Toast,
  Radio,
  RadioGroup,
  Uploader,
} from "vant";
import api from "@/utils/api";
export default {
  name: "UserInfo",
  components: {
    PageView,
    PageHeader,
    Form,
    Field,
    CellGroup,
    Button,
    Toast,
    Radio,
    RadioGroup,
    Uploader,
  },
  setup() {
    let userInfo = reactive({
      nickName: "",
      password: "",
      user_sex: "男",
      user_phone: "",
      user_email: "",
      confirm_password: "",
      user_photo: "",
    });

    const loading = ref(false);

    //BaseURL（64位）准备图片预览用的
    const { proxy } = getCurrentInstance();
    const store = useStore();
    //文件上传的列表图片预览
    const fileList = ref([
      {
        url: "http://home.softeem.xin:9544" + store.state.userInfo.user_photo,
      },
    ]);
    //路由
    const router = useRouter();
    const route = useRoute();

    //头像图片超过大小以后
    const onOversize = (file) => {
      Toast("图片大小不能超过500kb");
    };

    //文件上传成功后调用
    const afterRead = async (file) => {
      //调用api上传文件
      // File是内置的文件上传的0号单元（以数组的形式存在）;
      let results = await api.userInfo.uploadUserPhoto(file.file);
      //返回了一个地址
      // console.log(results);
      // 往fleList里面添加一个新的图片地址(远程服务器的图片地址)
      file.status = "done";
      fileList.value = [{ url: proxy.BaseURL + results, message: "上传成功" }];
      userInfo.user_photo = results;
    };

    //表单提交
    const onSubmit = (values) => {
      addUser();
    };
    const validatorPassword = (val) => {
      if (userInfo.confirm_password !== userInfo.password) {
        return "两次密码不一致";
      }
    };
    //添加用户后台交互的接口
    const addUser = async () => {
      Toast.loading({
        message: "注册中...",
        forbidClick: true,
        duration: 0,
      });

      //控制禁用（提交）按钮
      loading.value = true;
      //   模拟人多的时候
      setTimeout(async () => {
        try {
          //   发送请求
          let res = await api.userInfo.add(userInfo);
          //清除提示
          Toast.clear(true);
          Toast.success("注册成功");
          //   仓库存储用户信
          //   跳转页面
          //替换到历史堆栈（将当前的url替换掉）后退不到这个页面
          router.replace({ name: "Login" });
        } catch (error) {
          //   失败
          console.log(error);
          Toast.fail("注册失败");
        } finally {
          loading.value = false; //不管请求成功与否都终止掉加载圈圈
        }
      }, 2000);
    };
    // console.log(store.state.userInfo);
    //   带值
    userInfo.nickName = store.state.userInfo.nickName;
    userInfo.user_phone = store.state.userInfo.user_phone;
    userInfo.user_email = store.state.userInfo.user_email;
    userInfo.user_sex = store.state.userInfo.user_sex;

    return {
      loading,
      ...toRefs(userInfo),
      onSubmit,
      afterRead,
      fileList,
      onOversize,
      validatorPassword,
    };
  },
};
</script>

<style lang="scss" scoped></style>
